#!/usr/bin/python

import re

def append_automatically_managed_section(file_content,section_content,eol): # will overwrite if section already there
	BEGINNING=eol+'<FARMHAND_AUTOMATICALLY_MANAGED_SECTION>'+eol
	ENDING=eol+'</FARMHAND_AUTOMATICALLY_MANAGED_SECTION>'+eol
		
	start=file_content.rfind(BEGINNING)
	end=file_content.rfind(ENDING)
	
	# ?? make it more robust? find and pull out section with any eol scheme?
	if start<>-1 and end<>-1 and start<end:
		# allow whitespace after the section
		if end+len(ENDING)==len(file_content) or file_content[end+len(ENDING):].isspace():
			file_content=file_content[:start]
			
	file_content += BEGINNING + section_content + ENDING
	
	return file_content
	
print append_automatically_managed_section('dan was here',"hello world\nfoo bar\n",'\n')
print '-----'
print append_automatically_managed_section('dan was here\n<FARMHAND_AUTOMATICALLY_MANAGED_SECTION>\nhello world\nfoo bar\n</FARMHAND_AUTOMATICALLY_MANAGED_SECTION>\n','here is a new one','\n')